# 自定义过滤器
import functools

from flask import session, current_app, g

from info.models import User


def func_index_convert(index):
    index_dict = {
        1: "first",
        2: "second",
        3: "third"
    }
    return index_dict.get(index)


# 自定义装饰器
def user_login_data(f):  #
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        # 查询根路由有无user_id--展示登陆界面
        user_id = session.get('user_id')
        user = None
        if user_id:
            # TODO user传入模板，后端渲染登录展示
            # 已经登录过了
            try:
                user = User.query.get(user_id)
            except Exception as e:
                current_app.logger.error(e)
        g.user = user
        return f(*args, **kwargs)

    return wrapper


# def file_upload(data):
#     import qiniu
#     access_key = "kJ8wVO7lmFGsdvtI5M7eQDEJ1eT3Vrygb4SmR00E"
#     secret_key = "rGwHyAvnlLK7rU4htRpNYzpuz0OHJKzX2O1LWTNl"
#     bucket_name = "infonews"
#     q = qiniu.Auth(access_key, secret_key)
#     key = None
#     token = q.upload_token(bucket_name)
#     ret, info = qiniu.put_data(token, key, data)
#     if ret is not None:  # 上传成功返回文件名
#         return ret.get('key')
#     else:
#         raise Exception(info)

def file_upload(data):
    """
    上传文件
    :param data:  要上传的二进制数据
    :return: 文件服务器中的文件名称
    """

    import qiniu

    access_key = "kJ8wVO7lmFGsdvtI5M7eQDEJ1eT3Vrygb4SmR00E"
    secret_key = "rGwHyAvnlLK7rU4htRpNYzpuz0OHJKzX2O1LWTNl"
    bucket_name = "infonews" # 空间名称

    q = qiniu.Auth(access_key, secret_key)
    key = None  # 设置上传文件名, 如果设置None则生成随机名称

    token = q.upload_token(bucket_name)
    # 上传文件
    ret, info = qiniu.put_data(token, key, data)
    if ret is not None:  # 上传成功, 返回文件名
        return ret.get("key")
    else:
       raise BaseException(info)